package com.jsl.action;

import com.api.system.language.autoTranslate.MD5;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.workflow.request.todo.RequestStatusObj;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;


public class UserCodeGetAction {

    private static final Log log = LogFactory.getLog(DaibanAction.class);


    private static final String appSecret = "e89277cb47e64f3d9473c401b559ff11";
    private static final String appId = "d12733aa0b68498fa6e13e4843c171de";
    private static final String url = "https://www.fjjslds.com";
    private static final String CODE = "Biz_6M68XUSR";

    //

//    private static final String[] orgIds = {
//            "fc4f71b6f9b44c04b43dde99bcecdc0e",
//            "f9f865cd19414d1cad45f437e8528990",
//            "ea65324e6cca4009a3acb3acc21a3b3b",
//            "e418e1003a614f96abaa873e1ccd152f",
//            "dbbd7dd274ce42ff9b0efe7180773826",
//            "d930b1d81e4449309991df7bfd2c5d2c",
//            "d86e78ef40c14d94aaa7551e5f4a5aa0",
//            "c862a84c4076465aa4c72acd18b8e196",
//            "c6f698a311d041e3b279054456befeab",
//            "c0d7f565f0b84d2ba00404bfed4d512b",
//            "c081cab4d3ee4ef49efdd639294f84e7",
//            "b339303fa16e44debdcf34013789869b",
//            "ad7ece4c8904435f948d3e17407d37cc",
//            "f168797a14f84730be6ed0d87df945a1",
//            "d6f3d582428b4fe396509ac574df298b",
//            "c05c46b7d68b4c6c88208c834cdba6f6",
//            "96d84d7045b04b1c8e620025340d6c80",
//            "6cbdb360cd124e7bacdb794d4955f6a3",
//            "4934642cc8a342c5940896663f177c7c",
//            "3695cc1644724f1a9da377b9972df876",
//            "13c8298c2bd04b73bb31c43e5a09ba36",
//            "0f5dbd89895a4ad6af3ff6e348a05200",
//            "0db83192aa024acaabff2ade70aff311",
//            "98e67a3e1b7c4f16a7aa82c387700a2e",
//            "82b2b78ee4964f24be2bfb9c1cd8bb7d",
//            "75b0d738c7ff4581a537aa634f33768a",
//            "70c63c20892b4c1bb4f0450fc7b95e60",
//            "6a9aff4a2d764464bfe4aa3c80b5b66a",
//            "6634629ff3d3483da9fa151ab2bfc864",
//            "523763bf821741b6be57be53ed8bc1a7",
//            "4a87b5c7cb7f420baf9b300af8d23f6a",
//            "1bb3c86b4c9c494e93745daeeccc3866",
//            "1923e91780bd4b3a9cce58b61d2df260",
//            "17ff6609bacd44eaa3073866be46eb61",
//            "0c8bdeb9c99745c28bc964112ade85cb",
//            "05e67de0cd14456aa9d299faae397fa4",
//            "df56d7739af548b1abbd7a5271b9d09b",
//            "dd7064b9d4e24cac883ab010b9f14efd",
//            "d07e65c699b547cf8756406b3d2578e7",
//            "abd21d6c998441dd8c90ecc8e31d9e84",
//            "9c4a12e63427453cb9e1ad7050bb034e",
//            "742d515846074820a89ecc6d92f03220",
//            "6e8c93838e734cbe8bdac2c261533d10",
//            "2102b4b77f3b4a5b86d75a66aad28b8b"
//    };

    private static final String[] orgIds = {"6db2833fa17a4b28a44c0300619fd63b"};

    public static void main(String[] args) throws Exception {
        System.out.println("开始测试接口");

        RequestStatusObj requestStatusObj = new RequestStatusObj();
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(requestStatusObj);
        System.out.println(s);

        //   sendRequest();

    }


    /**
     * 签名生成函数
     *
     * @param map
     * @param allrowEmpty
     * @return
     */
    private static String mapSortToUrlParam(Map<String, String> map, Boolean allrowEmpty) {
        List<String> keys = new ArrayList<>(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                // 返回相反的compare
                return o1.compareTo(o2);
            }
        });
        Iterator<String> iter = keys.iterator();
        StringBuffer signStr = new StringBuffer();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = map.get(key);
            if (!allrowEmpty && value == null) {// 不允许值为空
                continue;
            }
            if (signStr.length() > 0) {
                signStr.append("&");
            }
            signStr.append(key).append("=").append(value);
        }
        //System.out.println(signStr.toString());
        return signStr.toString();
    }

    /**
     * <p>Title: postForm</p>
     * <p>Description: 请求</p>
     *
     * @param url
     * @param headMap
     * @param params
     * @return
     * @throws Exception
     */
    private static String postForm(String url, Map<String, Object> headMap, Map<String, String> params) throws Exception {
        try {
            // post请求
            HttpPost httpPost = new HttpPost(url);
            if (headMap != null && !headMap.isEmpty()) {// 头部
                for (String key : headMap.keySet()) {
                    httpPost.setHeader(key, headMap.get(key) != null ? headMap.get(key).toString() : "");
                }
            }
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    nvps.add(new BasicNameValuePair(key, params.get(key) != null ? params.get(key).toString() : ""));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            int socketTimeout = 30000;
            int connectionTimeout = 30000;
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                    .setConnectTimeout(connectionTimeout).build();// 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            // 发送请求
            HttpClient httpclient = null;
            httpclient = HttpClientBuilder.create().build();
            HttpResponse httpresponse = httpclient.execute(httpPost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            String body = EntityUtils.toString(entity, "UTF-8");
            return body;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private static void sendRequest() throws Exception {

        long timestamp = new Date().getTime();
        //生成签名的参数
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("appId", appId);
        param1.put("appSecret", appSecret);
        param1.put("timestamp", String.valueOf(timestamp));
        String param1str = mapSortToUrlParam(param1, true);
        String sign = MD5.md5(param1str);
        param1.put("sign", sign);
        //获取token
        String url1 = url + "/spiToken";
        String tokenresult = postForm(url1, null, param1);
        System.out.println("token:"+tokenresult);
        //解析结果中token[结果要判断，这里只是做个样例]
        JSONObject jsonObject = JSONObject.fromObject(tokenresult);
        //[结果要判断，这里只是做个样例]
        String token = jsonObject.getString("data");
        System.out.println("token:"+token);
        String filePath = "D:/sql_commands6.txt";

// 将文件流创建移到循环外部，使用try-with-resources自动关闭流
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) { // 第二个参数true表示追加模式
            for (String orgId : orgIds) {
                // 调用spi接口
                String url2 = url + "/intf";

                // 生成签名的参数
                Map<String, String> signParams = buildSignParams(orgId, timestamp);
                String sign2 = MD5.md5(mapSortToUrlParam(signParams, true));
                signParams.put("sign", sign2);

                Map<String, Object> head = buildHeaders(token);
                System.out.println(signParams);
                String jsonString = postForm(url2, head, signParams);
                ObjectMapper mapper = new ObjectMapper();

                // 解析 JSON
                JsonNode rootNode = mapper.readTree(jsonString);
                JsonNode dataNode = rootNode.get("data");

                // 循环写入当前orgId对应的SQL，此时流是打开的，内容会追加
                if (dataNode != null && dataNode.isArray()) { // 增加非空和数组判断，避免空指针
                    for (JsonNode node : dataNode) {
                        String userCode = node.get("userCode").asText();
                        String idcard = node.get("idcard").asText();
                        String phone = node.get("phone").asText();
                        // 拼接SQL语句
                        String sql = "update hrmresource set textfield1='" + userCode + "' where textfield1 is null  and mobile ='"+phone+"';";

                       // String sql = "update hrmresource set textfield1='" + userCode + "' where certificatenum='" + idcard + "' and  textfield1 is null;";
                        // 写入文件（每句SQL占一行）
                        writer.write(sql);
                        writer.newLine(); // 换行
                    }
                    System.out.println("orgId: " + orgId + " 对应的SQL已追加到文件");
                } else {
                    System.out.println("orgId: " + orgId + " 没有获取到有效数据");
                }
                Thread.sleep(3000);
            }
            System.out.println("所有SQL语句已成功写入文件：" + filePath);
        } catch (IOException e) {
            System.err.println("文件操作失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private static Map<String, String> buildSignParams(String orgId,long timestamp) {
        Map<String, String> params = new HashMap<>();
        params.put("code", CODE);
        params.put("appSecret", appSecret);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("orgCode", orgId);
        params.put("isChildren", "0");
        params.put("noPage", "1");
        return params;
    }

    private static Map<String, Object> buildHeaders(String token) {
        Map<String, Object> headers = new HashMap<>();
        headers.put("access_token", token);
        return headers;
    }

}
